package com.woniuxy.driverschool.config;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.woniuxy.driverschool.entity.User;
import com.woniuxy.driverschool.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author shichen
 * @create 2021-09-27-11:16
 */
//@Component
public class UserRealm extends AuthorizingRealm {

    private static final Log log = LogFactory.get();

    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("shiro：开始授权================doGetAuthorizationInfo");
        //去数据库的权限表查询当前用户的所有权限,获取当前用户
        Object primaryPrincipal = principals.getPrimaryPrincipal();
        log.debug("================查询指定用户的所有权限:"+primaryPrincipal);
        Collection<String> permissions=new ArrayList<String>();
        permissions.add("user:select");
        permissions.add("user:update");
        permissions.add("user:insert");
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(permissions);
        log.info("shiro：授权结束================doGetAuthorizationInfo");
        return authorizationInfo;

    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("shiro：开始认证登录");
        // get user from token
        String principal = (String) token.getPrincipal();
        User user = userService.getUserByUserName(principal);
        if(user==null){
            return null;
        }
        // 得到密码
        String credentials = user.getPassword();
        // 密码比对
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(principal, credentials, this.getName());

        log.info("shiro：认证登录成功！");
        return authenticationInfo;

    }
}
